package ee.az.tetris.worker;

import ee.az.tetris.Dispatcher;
import ee.az.tetris.Glass;
import ee.az.tetris.event.BlocksRemovedEvent;
import ee.az.tetris.event.Event;
import java.awt.Color;

/**
 * @author Artur Zinatullin (artur.zinatullin@gmail.com) 2010
 */
public class LineRemovalWorker extends Worker {

	private final Dispatcher dispatcher;

	public LineRemovalWorker(Glass glass, Dispatcher dispatcher) {
		super(glass);
		this.dispatcher = dispatcher;
	}

	@Override
	public void work(Event event) {
		for (int row = getGlass().getRowCount()-1; row >= 0 ; row--) {
			boolean canShift = true;
			for (int col = 0; col < getGlass().getColumnCount(); col++) {
				Color value = getGlass().getValue(col, row);
				if (!Glass.FIXED.equals(value)) {
					canShift = false;
				}
			}
			if (canShift) {
				shiftDown(row);
				dispatcher.dispatch(new BlocksRemovedEvent());
			}
		}
	}

	public void shiftDown(int start) {
		for (int row = start-1; row >= 0 ; row--) {
			for (int col = 0; col < getGlass().getColumnCount(); col++) {
				getGlass().setValue(getGlass().getValue(col, row), col, row+1);
			}
		}
	}
}
